什么是Cookie
Cookie是在浏览器访问某个Web资源时,由Web服务器在HTTP响应消息头中通过Set-Cookie字段发送给浏览器的一组消息。
浏览器会根据Set-Cookie字段中的Cookie数据决定是否保存这些Cookie,当浏览器下次访问这个资源时,会自动读取这些被保存的Cookie,并加到HTTP请求消息头的Cookie字段,Web服务器会根据Cookie字段中的内容作出相应的处理。
一个Cookie只能表示一个key-value对,这个key-value对由Cookie名和Cookie值组成,Web服务器可以给一个Web浏览器发送多个Cookie,但每个Cookie的大小一般被限制为4KB。
操作Cookie
在Servlet API中使用java.servlet.http.Cookie
类来封装一个Cookie消息,在HttpServletResponse
接口中定义了一个addCookie
方法来向浏览器发送Cookie消息,在HttpServletResquest
接口中定义了一个getCookies
方法来读取浏览器传递过来的Cookie消息,Cookie类只有一个构造方法:
|
|
其中name表示Cookie名(在name参数值中不能包含任何空格字符、逗号、分号,并且不能以$字符开头),Value表示Cookie的值。
Cookie类中有以下一些常用的方法:
- getName():返回Cookie的名称
- setValue()和getValue():设置和返回Cookie的值
- setMaxAge()和getMaxAge():设置和返回Cookie在客户机上的有效时间,也就是Cookie在客户机上的有效秒数,如果为0,表示当Cookie消息发送到客户端后被浏览器立即删除,如果设置为负数,表示浏览器并不会把这个Cookie保存在硬盘上,这种Cookie称为临时Cookie(保存在硬盘上的Cookie称为永久Cookie),它们只存在于当前浏览器的进程中,当浏览器关闭后,Cookie自动失效。
- setPath():设置客户端访问什么路径传递Cookie对象,如果在创建某个Cookie时未设置它的path属性,那么该Cookie只对当前访问的Servlet所在的Web路径及其子路径有效,如果要想使Cookie对整个Web站点中的所有可访问的路径都有效,需要将path属性值设置为”/“。
举例
通过Cookie技术读写客户端信息
SaveCookie.java
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667package com.glemotree.servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/*** Servlet implementation class SaveCookie*/public class SaveCookie extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public SaveCookie() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub}protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/heml;charset=UTF-8");PrintWriter out = response.getWriter();// 设置临时Cookie,临时Cookie不需要设置MaxAge属性Cookie tempCookie = new Cookie("temp", "87654321");// 添加临时Cookieresponse.addCookie(tempCookie);Cookie cookie = new Cookie("cookie", "6666");cookie.setMaxAge(0);response.addCookie(cookie);String user = request.getParameter("user");if (user != null) {Cookie userCookie = new Cookie("user", user);userCookie.setMaxAge(60 * 60 * 24);// userCookie.setPath("/");response.addCookie(userCookie);}// 转发到ReadCookie,并读出已经保存的CookieRequestDispatcher readCookie = getServletContext().getRequestDispatcher("/servlet/ReadCookie");// 开始转发readCookie.include(request, response);}}ReadCookie.java
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263package com.glemotree.servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/*** Servlet implementation class ReadCookie*/public class ReadCookie extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public ReadCookie() {super();// TODO Auto-generated constructor stub}protected Cookie getCookieValue(Cookie[] cookies, String name) {if (cookies != null) {for (Cookie cookie : cookies) {if (cookie.getName().equals(name)) {return cookie;}}}return null;}/*** @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)*/protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubresponse.setContentType("text/html;charset=UTF-8");PrintWriter out = response.getWriter();Cookie tempCookie = getCookieValue(request.getCookies(), "temp");if (tempCookie != null) {out.println("临时Cookie值: " + tempCookie.getValue() + "<br>");} else {out.println("临时Cookie未设置!<br>");}Cookie cookie = getCookieValue(request.getCookies(), "cookie");if (cookie != null) {out.println("cookie: " + cookie.getValue() + "<br>");} else {out.println("cookie已经被删除!<br>");}Cookie userCookie = getCookieValue(request.getCookies(), "user");if (userCookie != null) {out.println("user: " + userCookie.getValue() + "<br>");} else {out.println("user未设置!<br>");}}}对上面的代码我进行一下简要的解释:
- 设置临时Cookie是不需要设置maxAge属性的
- 添加一个Cookie可以调用response的addCookie方法进行添加
- setMaxAge(0)表示Cookie到达浏览器后会被立即删除
- 转发的过程是服务器端自己的过程,是不经过浏览器的,此时URL地址也是不变的
- 临时Cookie只要不关闭浏览器仍然是可以读取到的,一旦关闭浏览器重新访问,cookie就不存在了